<?php
namespace cms\modules\backend\controllers;

use Yii;
use yii\db\Expression;
use cms\controllers\AuthController;
use app\models\Nav;
use app\models\VueRouter;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;
use common\behaviors\Sort;


class NavController extends AuthController
{

    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

    /*内容列表*/
    public function actionNavList()
    {
        if(isset($this->get['type']) and $this->get['type'] == 'ele'){
            $flag = 'ele';
        }else{
            $flag = '';
        }
        $lang = isset($this->get['lang'])?$this->get['lang']:'zh';
        // P($lang);
        $navList = Nav::getTreeList((new Nav)::find(), $this->app_id, $flag, $lang);
        // P($navList);
        return Tool::showRes([0, '获取成功'], $navList);
    }

    /*添加导航*/
    public function actionAddNav()
    {
        if(Yii::$app->request->isPost){
            $nav = new Nav;
            if($id = $nav->addNav($this->post, $this->app_id)){
                if(!empty($this->post['VueRouter']['path'])
                 and !empty($this->post['VueRouter']['name']) 
                 and !empty($this->post['VueRouter']['component'])){
                    /*添加VUE 路由*/
                    $vueRouter = new VueRouter;
                    $vueRouter->addRouter($this->post, $id);
                }

                $backInfo = [0, '添加导航成功'];//返回信息
            }else{
                if($nav->hasErrors()){
                    $backInfo = ErrMap::getError(10005);//返回信息
                    $exception = $nav->getErrors();//异常信息
                }
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }


    /*
    修改导航
    */
    public function actionModifyNav()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $navid = isset($this->get['id'])?$this->get['id']:'';
            if($navid){
                $nav = Nav::find()
                        ->select(['{{%nav}}.navid', '{{%nav}}.name', 'icon', 'parentid', 'preview', 'outside', 'catid', 'url_target', 'url', 'args', 'child_route', 'display'])
                        ->where('{{%nav}}.navid = :id', [':id' => $navid])
                        ->joinWith('vueRouter')
                        ->asArray()->one();
                if(!is_null($nav)){
                    if(!empty($nav['preview'])){
                        $nav['preview'] = explode(',', $nav['preview']);
                    }
                    if(!empty($nav['args'])){
                        $nav['args'] = explode('||', $nav['args']);
                    }

                    return Tool::showRes([0, '获取成功'], $nav);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $navid = isset($this->post['Nav']['id'])?intval($this->post['Nav']['id']):'';
            $allMod = isset($this->post['Nav']['allMod'])?intval($this->post['Nav']['allMod']):true;
            if(!$navid){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                /*修改导航信息*/
                $nav = new Nav;
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    if(!$nav->modifyNav($this->post, $navid, $allMod)){
                        $pass = false;
                        if($nav->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $nav->getErrors();//异常信息
                        }
                    }

                    if($pass){
                        if(!empty($this->post['VueRouter']['path'])
                         and !empty($this->post['VueRouter']['name']) 
                         and !empty($this->post['VueRouter']['component'])){
                            /*添加、修改VUE 路由*/
                            $vueRouter = new VueRouter;
                            if($pass and !$vueRouter->addRouter($this->post, $navid)){
                                $pass = false;
                                if($vueRouter->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $vueRouter->getErrors();//异常信息
                                }
                            }
                        }else{
                            $vueRouter = new VueRouter;
                            $vueRouter->deleteAll('navid = :id', [':id' => $navid]);
                        }
                    }
                    
                    if($pass){
                        $backInfo = [0, '修改导航成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }


    /*删除导航,包括子导航（真删除）*/
    public function actionDeleteNav()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        if($id){
            $nav = new Nav;
            if(($res = $nav->deleteNav($id)) === true){
                $backInfo = [0, '删除导航成功'];//返回信息
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), '') ) != 'boolean'){
                    return $res;
                };
            }else{
                return Tool::showRes(ErrMap::getError($res));
            }
        }
        return Tool::showRes(ErrMap::getError($res));
    }

    /*
    排序
    tree型数据，是按照sort正序排列
    */
    public function actionSetSort()
    {
       if(Yii::$app->request->isPost){
            // P($this->post);
            //取出被排序的数据
            $sortId = isset($this->post['sort'])?$this->post['sort']:'';
            //目标对象  ‘before’在之上面，否则在下面
            $targetId = isset($this->post['target'])?$this->post['target']:'';
            if($sortId and $targetId){
                if($this->setSortTreeList(new Nav, $sortId, $targetId, $this->post['location'])){
                    $backInfo = [0, '设置导航排序成功'];//返回信息
                }
            }
            // P($backInfo);

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };


       }
       return Tool::showRes(ErrMap::getError(10005));
    }

}
